import { logout, getToken } from './auth';
import { message } from 'antd';

let PopUp = false;

const limitPopUp = (callback: () => void) => {
  if (!PopUp) {
    PopUp = true;
    callback();
  }
  setTimeout(() => {
    PopUp = false;
  }, 100);
};

export const request = {
  timeout: 20 * 1000,
  errorConfig: {
    adaptor: (resData: any) => {
      return {
        ...resData,
        showType: 2,
        errorMessage: resData.errorMsg || '请求失败',
      };
    },
  },

  errorHandler: (error: { response: any }) => {
    if (!error.response) {
      limitPopUp(() => message.error('请求超时，请检查网络！'));
    }
  },

  requestInterceptors: [
    (url: string, options: any) => {
      const token = getToken();
      const requestUrl = url;
      return {
        url: requestUrl,
        options: {
          ...options,
          interceptors: true,
          headers: { Authentication: token || '', ...options.headers },
        },
      };
    },
  ],
  responseInterceptors: [
    async (response: { status: number }) => {
      const { status } = response;
      if (status === 401) {
        limitPopUp(() => message.error('登录失效'));
        logout();
      }
      if (status > 500) {
        limitPopUp(() => message.error('服务器内部错误'));
      }
      return response;
    },
  ],
};
